package com.mp.approvalreq.util;

import com.mp.approvalreq.entity.dto.RequestInfoDTO;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class ApprovalListUtils {

	/**
	 * 获取分页结果
	 */
	public static List<RequestInfoDTO> getApprovalPages(List<RequestInfoDTO> list, int dataNum, int page) {
		List<RequestInfoDTO> res = new ArrayList<>(dataNum);
		int count = 0;
		for (int i = (page - 1) * dataNum; i < list.size() && count < dataNum; i++) {
			count++;
			RequestInfoDTO requestInfoDTO = list.get(i);
			requestInfoDTO.setTotalCount(list.size());
			res.add(requestInfoDTO);
		}
		return res;
	}

	public static void setRelaPeopleNames(List<RequestInfoDTO> requestInfoDTOs, int companyId) throws Throwable {
		if (ListHelper.isNullEmpty(requestInfoDTOs)) {
			return;
		}

		List<Integer> contactIds = new ArrayList<>(requestInfoDTOs.size());
		for (RequestInfoDTO requestInfoDTO : requestInfoDTOs) {
			contactIds.add(requestInfoDTO.getApplicant());
			if (StringUtils.isNotEmpty(requestInfoDTO.getRelaPeopleContactIds())) {
				contactIds.addAll(ListHelper.string2IntegerList(requestInfoDTO.getRelaPeopleContactIds()));
			}
		}

		UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
		List<User> users = userService.getUserBaseInfoListByContactIds(companyId, ListHelper.list2string(contactIds));
		Map<Integer, User> userMap = ApprovalUtils.getUserMap(users);

		for (RequestInfoDTO requestInfoDTO : requestInfoDTOs) {
			User user = userMap.get(requestInfoDTO.getApplicant());
			requestInfoDTO.setApplicantName(user.getContactName());

			if (StringUtils.isNotEmpty(requestInfoDTO.getRelaPeopleContactIds())) {
				List<User> relaUsers = ApprovalUtils.getUsers(userMap, requestInfoDTO.getRelaPeopleContactIds());
				String relaPeopleNames = ApprovalUtils.getUsersContactName(relaUsers);
				requestInfoDTO.setRelaPeopleNames(relaPeopleNames);
			}
		}
	}


}
